package com.example.paging.network

import com.example.paging.entity.HomeVO
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine

object ArticleNetwork {

    private val articleService = ServiceCreator.create<ArticleService>()

    suspend fun getHomeVo(page: Int) = articleService.getArticlePage(page).await()

    suspend fun getHomeArticles(page: Int): HomeVO.Data {
        return articleService.getHomeArticles(page).data
    }


    private suspend fun <T> Call<T>.await(): T {
        return suspendCoroutine { continuation ->
            enqueue(object : Callback<T> {
                override fun onFailure(call: Call<T>, t: Throwable) {
                    continuation.resumeWithException(t)
                }

                override fun onResponse(call: Call<T>, response: Response<T>) {
                    val body = response.body()
                    if (body != null) continuation.resume(body)
                    else continuation.resumeWithException(RuntimeException("response is null"))
                }
            })
        }
    }

}